package com.sevenluo.netty.learn.server.codec.handler;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jmx.JmxReporter;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author: 程序员七哥
 * @date: 2022-02-02
 * @description: 统计当前系统的连接总数，此 handler 是可以共享的
 */
@ChannelHandler.Sharable // 表示这个 handler 是可以共享的，可以重复加入 pipeline，否则当多个客户端连接就会失败
public class MetricHandler extends ChannelDuplexHandler {

    private AtomicLong totalConnectionNumber = new AtomicLong();

    {
        MetricRegistry metricRegistry = new MetricRegistry();
        metricRegistry.register("totalConnectionNumber", new Gauge<>() {
            @Override
            public Object getValue() {
                return totalConnectionNumber.longValue();
            }
        });

        // 添加到 console，定时打印
        ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(metricRegistry).build();
        consoleReporter.start(5, TimeUnit.SECONDS);

        // jmx 是实时的，只要启动即可
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 监测到连接自增
        totalConnectionNumber.incrementAndGet();
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 连接断开减 1
        totalConnectionNumber.decrementAndGet();
        super.channelInactive(ctx);
    }
}
